package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class ApArticleServiceImpl extends
        ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    AuthorMapper authorMapper;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 根据文章id查询文章内容
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArtilceInfo(ArticleInfoDto dto) {
        //1.校验参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询
        //config
        ApArticleConfig articleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, dto.getArticleId()));
        if (articleConfig == null
                || articleConfig.getIsDown()
                || articleConfig.getIsDelete()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已下架");
        }
        //content
        ApArticleContent articleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getArticleId()));
        if (articleContent == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("config", articleConfig);
        map.put("content", articleContent);
        return ResponseResult.okResult(map);
    }

    /**
     * 根据参数加载文章列表
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto,Short loadtype) {
        //1.参数校验
        if (dto == null) {
            dto = new ArticleHomeDto();
        }
        //2.参数值处理
        //标签
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //页码
        Integer size = dto.getSize();
        if (size == null || size >= 10 || size <=0) {
            size = 10;
        }
        //时间
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }

        // 类型 1 or 2
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)
                && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        List<ApArticle> list = apArticleMapper.loadArticleList(dto, loadtype);

        // 处理图片封面
        ResponseResult result = ResponseResult.okResult(list);
        result.setHost(webSite);
        return result;
    }

    /**
     * 保存文章信息三张表
     *
     * @param articleDto
     * @return 返回文章id主键
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);

        //1 设置作者id
        String authorName = articleDto.getAuthorName();
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getName, authorName));
        if (apAuthor == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "作者不存在");
        }
        apArticle.setAuthorId(apAuthor.getId().longValue());

        if (apArticle.getId() == null) { // 新增
            //2 补充其他属性Article
            apArticle.setComment(0); // 评论
            apArticle.setViews(0);  // 阅读
            apArticle.setCollection(0); // 收藏
            apArticle.setLikes(0); // 点赞

            //3 保存Article数据到数据库
            save(apArticle);  // 返回apArticleID

            //4 保存ArticleConfig数据到数据库
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setIsForward(true);
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsDelete(false);
            apArticleConfigMapper.insert(apArticleConfig);

            //5 保存ArticleContent数据到数据库
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(articleDto.getContent());
            apArticleContentMapper.insert(apArticleContent);

        } else { // 修改

            // 先查询后改
            ApArticle article = getById(apArticle.getId());
            if (article == null) {
                log.info("ApArticle getById is null: {}", articleDto.getId());
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
            }
            // 修改 apArticle****
            updateById(apArticle);

            // 文章内容修改
            ApArticleContent articleContent = apArticleContentMapper.selectOne(Wrappers
                    .<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
            if (articleContent == null) {
                log.info("articleContent  is null: {}", articleDto.getId());
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章内容不存在");
            }
            articleContent.setContent(articleDto.getContent());
            apArticleContentMapper.updateById(articleContent);
        }


        //6 封装返回结果id
        return ResponseResult.okResult(apArticle.getId());
    }


}
